package cn.anl.service;

import cn.anl.constant.RedisConstant;
import cn.anl.mapper.SysRequestPathMapper;
import cn.anl.pojo.SysPermission;
import cn.anl.pojo.dto.SysRequestPathDTO;
import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author 安奈
 * @CreateTime 2024-07-06  17:46
 * @Desc 请求路径权限数据初始化类
 */
@Slf4j
@Component
public class UserRequestServiceImpl {
    @Resource
    private RedisService redisService;
    @Resource
    private SysRequestPathMapper sysRequestPathMapper;

    /**
    * @Author 安奈
    * @Desc @TODO 目前初始化到redis的只有url和permissionCode,url还需要加上请求方法（POST：url,GET:url）
    */
    @PostConstruct
    public void initRequestPath() {
        redisService.deleteObject(RedisConstant.REQUEST_PATH.getKey());
        log.info("@PostConstruct方法被执行了，进行了一些初始化操作...");
        //根据角色权限获取所有的请求地址以及权限码permissionCode
        List<SysRequestPathDTO> requestPaths = sysRequestPathMapper.finAllPathAndPermission();
        Map<String, List<String>> resourceRolesMap = new TreeMap<>();

        for (SysRequestPathDTO requestPath : requestPaths) {
            ArrayList<String> permissionCode = new ArrayList<>();
            //这里拿到的是Permission对象，需要遍历取出PermissionCode
            for (SysPermission sysPermission : requestPath.getPermissionCode()) {
                permissionCode.add(sysPermission.getPermissionCode());
            }
            resourceRolesMap.put(requestPath.getUrl(), permissionCode);
        }
        log.info(resourceRolesMap.toString());
        //将路径对应的所有PermissionCode存入redis
        redisService.setCacheMap(RedisConstant.REQUEST_PATH.getKey(), resourceRolesMap);
    }
}
